Repository navigation
feat(leagues): add weekly leagues with Redis standings and Sunday rollover - #382
Merged
VarshithReddy2006 merged 2 commits intoNov 16, 2026
Conversation
…lover
Adds the weekly leagues module (Bronze to Grandmaster):
- LeagueStanding model plus migration 0012-leagues (indexes, and
leagues.participate=false backfilled on existing user settings)
- cohort partitioning into groups of ~30, a leftover under 10 is merged
into the previous cohort
- live standings as Redis sorted sets league:{weekKey}:{division}:{cohortId},
behind a small LeagueScoreStore interface so tests use an in-memory fake
- league-score worker: the XP processor enqueues every awarded (>0 XP)
ledger write and the worker ZINCRBYs the user's cohort, once per award
- weekly rollover worker (Sunday 00:00 UTC repeatable job): finalizes
ranks, promotes top 20%, demotes bottom 20%, places everyone in new
cohorts and sends a league_week_finalized SSE event; idempotent per week key
- GET /api/v1/leagues/current and PUT /api/v1/leagues/participation
- Redis can be rebuilt from the XpTransaction ledger
Closes VarshithReddy2006#353
Signed-off-by: Abhishek <abhishekcse2004@gmail.com>
Owner
|
All CI checks passed! However, PR #380 was just merged into Please merge the latest |
6 tasks
Owner
|
Resolved merge conflict in \�ackend/src/shared/events/eventContract.ts\ against main and squash-merged! Thanks @Anshuu2004. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds the weekly leagues module from #353: Bronze to Grandmaster divisions, cohorts of about 30, live standings in Redis sorted sets, a score worker fed by XP awards, and a Sunday 00:00 UTC rollover that promotes the top 20%, demotes the bottom 20% and is safe to run more than once for the same week.
What changed
backend/src/db/models/leagueStanding.model.ts(new) +leagueStandingIndexes.ts: one row per user per week (weekKey,division,cohortId,statusactive/finalized,joinedAt, finalpoints/rank/outcome/nextDivision). Unique index on(weekKey, userId). The row is created asactivewhen a user is placed in a cohort and flipped tofinalizedby the rollover, so it is also where the cohort membership lives (needed to rebuild Redis).backend/src/db/models/userSettings.model.ts:leagues.participate, defaultfalse.backend/src/db/migrations/0012-leagues.ts+run-leagues.ts+npm run migrate:leagues: creates the indexes, backfillsleagues.participate: falseon existing settings,downdrops the indexes and the settings field (standing rows are kept). Number 0012 because 0011 is the last one on main, the issue text says 0015.modules/leagues/cohorts.ts: seeded deterministic split into cohorts of 30; a leftover under 10 is merged into the previous cohort; late joiners go into the emptiest cohort under 30, else a new one.modules/leagues/scoreStore.ts: smallLeagueScoreStoreinterface (incrementOnce,seed,replace,remove,ranked,exists,expire) and the ioredis implementation. Increments run as one Lua script (SADDan applied-id, thenZINCRBY), so a replayed award counts once.modules/leagues/leagues.service.ts: join/opt-out,recordXpAward, standings read (ZREVRANGE ... WITHSCORESequivalent, username/avatar fromUser, rank, points, countdown to the reset), and rebuild of a cohort or a whole week fromXpTransaction. A missing Redis set is rebuilt on read and also before a rollover ranks it.modules/leagues/rollover.ts:runWeeklyRollover(weekKey). Phase 1 finalizes each cohort (rank, points, outcome, next division), phase 2 places opted-in users in new cohorts for the next week with$setOnInsert, phase 3 seeds the new Redis boards withZADD NXand sets a 14 day TTL on the old ones, then sends an SSEleague_week_finalizedevent per finalized user.modules/leagues/workers/leagueScore.worker.ts: BullMQ worker on queueleague-scoreplusenqueueLeagueScore.modules/leagues/workers/weeklyRollover.worker.ts: worker onleague-rolloverplusscheduleWeeklyRollover(repeatable0 0 * * 0, tz UTC). The job finalizes the week before the one it runs in, so a late run still finalizes the right week.modules/leagues/leagues.routes.ts, mounted inroutes/index.ts:GET /api/v1/leagues/currentandPUT /api/v1/leagues/participation({ participate: boolean }, strict zod).modules/xp/processor.ts: after an award is committed and it is more than 0 XP, enqueue a league score job (failure is logged and ignored, it never fails the XP award).shared/jobs/types.ts: queue names and job data types.workers/worker-runtime.ts: the score worker runs with thexprole, the rollover worker (and its schedule) with themaintenancerole.worker-runtime.test.tsupdated for the two new workers.league_week_finalizedevent type,league.week.finalizeddomain event type and allowlist entry.README.md: endpoint row and a short migration/ops note.What I used instead of an
xp.awardedeventThe
xp.awardedtype exists in the event contract and the SSE bridge, but nothing on main publishes it (the XP processor only calls the in-process SSEeventBus). So I did not invent a publisher for the whole event system. Instead the XP processor, which is the only place that writesXpTransactionrows, enqueues oneleague-scorejob per committed award with{ userId, sourceType, sourceId, xpAwarded, occurredAt }. Same data as thexp.awardedpayload plus the ledger timestamp. If anxp.awardedpublisher lands later, the worker handler (processLeagueScoreJob) can be called from that consumer unchanged.Anti-gaming: the processor writes no ledger row and returns early for a focus session that does not qualify, and
xpAwarded > 0is required before anything is enqueued, so those add 0. Only the server-written amount is used, nothing comes from the client.How I tested
Run from
backend/, one file at a time, with the repo'ssrc/__tests__/vitest.setup.ts(in-memory MongoDB,ioredisandbullmqmocked),NODE_OPTIONS="--disable-wasm-trap-handler --max-old-space-size=3072":Existing files I ran to check I did not break anything near my changes, all passing:
xp-processor.test.ts(31),xp-concurrency.test.ts(5),consumer-inbox.test.ts(18),ops-cross-process-dlq.test.ts(4),dlq.test.ts(13),settings.persistence.test.ts(11).npx tsc --noEmit: the same 5 errors as clean main (the unbuilt@devtrack/ats-coreimport and 3 implicitanyinResumeMLService.ts), none in the files of this PR.The new module does not exist on main, so every league test fails there by definition. For the one change to existing behaviour I checked it directly: with
processor.tsreverted to main,xp-league-hook.test.tsfails on "enqueues the ledger-backed amount once" (the three negative cases pass on main as expected).What the tests cover (Redis is
FakeScoreStore, an in-memory sorted set with ZREVRANGE ordering; no Redis server is used anywhere):c2, 3 concurrent joins give one row, tail-merge for leftovers under 10, deterministic for a seedrebuildWeekFromLedger, on-demand rebuild on a standings read, and a rollover after a flush ranks from the ledger (only XP of that week and after the user joined counts)true, runs twice, rollback runs twice and on a DB that never migratedNot tested / notes
docs/v2/*(DATABASE_SCHEMA_V2.md section 5.9, BACKEND_SPECIFICATION_V2.md section 13, MODULE_IMPLEMENTATION_PLAN.md section 15.4) do not exist on main, so I could not update them. I put a short note in the README instead.floor(size * 20 / 100)each, with no minimum-points guard, so a participant with 0 points can be promoted if the cohort is mostly idle. Equal scores keep the Redis order (reverse lexicographic by user id).weekKey = Sunday date (UTC), not ISO weeks, because the week starts on Sunday.Closes #353